package pro.shuangxi.common.aop;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import mybatisplus.pojo.Users;
import mybatisplus.service.IUsersService;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import pro.shuangxi.common.vo.Result;
import pro.shuangxi.common.aop.annotation.Token;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @author ：mengshx
 * @date ：Created in 2021/4/10 16:44
 * @description：鉴权
 */
@Component
@Aspect
public class TokenFilter {
    @Autowired
    IUsersService usersService;
    //配置切点
    @Pointcut("@annotation(pro.shuangxi.common.aop.annotation.Token)")
    public void TokenFilter(){};
    @Around("TokenFilter()")
    public Object token(ProceedingJoinPoint pjp) throws Throwable {
        //获取request和response
        System.out.println("进入aop");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        HttpServletResponse response = attributes.getResponse();
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Token annotation = signature.getMethod().getAnnotation(Token.class);
        if (annotation!=null){
            System.out.println("该接口正在鉴权");
            String token = request.getHeader("token");
            if(StringUtils.isNotEmpty(token)){
                Users user = usersService.getOne(new QueryWrapper<Users>().eq("token", token));
                if (user != null && user.getUpdatetime().getTime()-new Date().getTime() < 1000 * 60 * 60 * 24 * 7) {
                            Object o = pjp.proceed();
                            return o;

                }

            }
            System.out.println("token鉴权失败");
            Result error = Result.error("token鉴权失败,请重新登陆");
            ObjectMapper mapper = new ObjectMapper();
            String result = mapper.writeValueAsString(error);
            response.setHeader("Content-Type","text/html;charset=UTF-8");
            response.getWriter().write(result);
            return null;
        }else {
            Object o = pjp.proceed();
            return o;
        }
    }
}
